package cn.demoncat.util.io;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URLConnection;

/**
 * 
 * 关闭资源
 */
public final class CloseUtil {
 
	private static final Logger LOG = LoggerFactory.getLogger(CloseUtil.class);
	
	/**
	 * 刷新输出流，强制写出缓存中的剩余数据
	 * 
	 * @param out
	 */
	public static void flush(OutputStream out){
		try {
			out.flush();
		} catch (IOException e) {
			LOG.warn("刷新OutputStream缓存区失败", e);
		}
	}
	/**
	 * 刷新输出流，强制写出缓存中的剩余数据
	 * 
	 * @param out
	 */
	public static void flush(Writer out){
		try {
			out.flush();
		} catch (IOException e) {
			LOG.warn("刷新Writer缓存区失败", e);
		}
	}
	/**
	 * 关闭流资源
	 * 
	 * @param close InputStream/OutputStream/Writer/Reader/Socket/Selector/ServerSocket等
	 */
	public static void close(Closeable close) {
		if (close != null) {
			try {
				close.close();
			} catch (IOException e) {
				LOG.warn("关闭IO资源失败", e);
			}
		}
	}

	/**
	 * 关闭流资源
	 *
	 * @param closes InputStream/OutputStream/Writer/Reader/Socket/Selector/ServerSocket等
	 */
	public static void closeAll(Closeable... closes) {
		if (closes != null) {
			try {
				for (Closeable close : closes) {
					if (close != null) {
						close.close();
					}
				}
			} catch (IOException e) {
				LOG.warn("关闭IO资源失败", e);
			}
		}
	}

	/**
	 * 关闭URLConnection连接
	 * 
	 * @param conn HttpURLConnection
	 */
	public static void close(URLConnection conn){
		if (conn != null) {
			if (conn instanceof HttpURLConnection) {
	            ((HttpURLConnection) conn).disconnect();
	        }
		}
	}
}
